import styles from "@styles/login.module.less";
import Header from "@shared/header";
import Back from "@shared/back";
import { z } from "zod";
import { SubmitHandler, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useLoginMutation } from "@service/authEndpoints";
import toast from "react-hot-toast";
import { useLocation, useNavigate } from "react-router-dom";
import SendMsgCode from "@pages/login/widgets/sendMsgCode";

export interface LoginFormState {
  mobile: string;
  code: string;
}

const schema = z.object({
  mobile: z
    .string({
      required_error: "请检查mobile字段是否存在",
      invalid_type_error: "请检查mobile字段的类型是否正确",
    })
    .min(1, "请输入手机号")
    .regex(/^1[3-9]\d{9}$/, "请输入正确格式的手机号"),
  code: z
    .string({
      required_error: "请检查code字段是否存在",
      invalid_type_error: "请检查code字段的类型是否正确",
    })
    .length(6, "验证的长度是6"),
});

export default function LoginPage() {
  // 创建表单对象
  const {
    register,
    handleSubmit,
    formState: { errors, isValid },
    // 获取字段状态
    getFieldState,
    // 获取表单控件对象的值
    getValues,
  } = useForm<LoginFormState>({
    resolver: zodResolver(schema),
    mode: "onChange",
    defaultValues: { mobile: "13911111111", code: "246810" },
  });

  // 获取登录请求方法和相关状态
  const [login] = useLoginMutation();
  // 获取跳转方法
  const navigate = useNavigate();

  const location = useLocation();

  // 表单提交
  const onSubmit: SubmitHandler<LoginFormState> = (state) => {
    // 发送登录请求
    // 特别注意事项, 用于发送请求的方法默认永远返回成功状态的 promise 对象
    login(state)
      // 返回原始的 Promise 对象
      .unwrap()
      .then(() => {
        // 登录成功
        toast.success("登录成功");
        // 跳转到首页
        navigate(location.state?.from || "/");
      })
      .catch((error) => {
        if (typeof error !== "undefined" && "status" in error) {
          const data = error.data as GeekResponse<null>;
          toast.error(data.message);
        }
      });
  };

  // useEffect(() => {
  //   if (isSuccess) {
  //     // 登录成功
  //     toast.success("登录成功");
  //     // 跳转到首页
  //     navigate("/");
  //   }
  // }, [isSuccess, navigate]);

  // error 对象的类型是联合类型: FetchBaseQueryError | SerializedError | undefined
  // undefined: 没有错误的时候, 错误对象就是 undefined
  // FetchBaseQueryError: 服务端返回错误时
  // SerializedError: 客户端代码执行错误时

  // useEffect(() => {
  //   if (typeof error !== "undefined" && "status" in error) {
  //     const data = error.data as GeekResponse<null>;
  //     toast.error(data.message);
  //   }
  // }, [error]);

  return (
    <div className={styles.login_page}>
      <Header title={""} left={<Back />} />
      <h2>短信登录</h2>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className={styles.form_item}>
          <input
            type="text"
            placeholder="请输入手机号"
            {...register("mobile")}
          />
          {errors.mobile && (
            <p className={styles.error_message}>{errors.mobile.message}</p>
          )}
        </div>
        <div className={styles.form_item}>
          <input {...register("code")} type="text" placeholder="请输入验证码" />
          {/* 如果验证码正在发送, className={styles.active} */}
          <SendMsgCode getFieldState={getFieldState} getValues={getValues} />
          {errors.code && (
            <p className={styles.error_message}>{errors.code.message}</p>
          )}
        </div>
        <button disabled={!isValid} className={styles.login_button}>
          登录
        </button>
      </form>
    </div>
  );
}
